package main

import (
	"net"
	"strings"

	_net "github.com/shirou/gopsutil/net"
)

func get_mac_address() string {
	ip, _ := GetLocalIP()
	mac, _ := GetLocalMac(ip[0])
	return mac
}

func GetLocalIP() ([]string, error) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	list := []string{}
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()
			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						list = append(list, ipnet.IP.String())
					}
				}
			}
			if len(list) > 0 {
				return list, nil
			}
		}
	}
	return nil, err
}

func GetLocalMac(ip string) (string, error) {
	// 获取本机的MAC地址
	interfaces, err := _net.Interfaces()
	if err != nil {
		return "", err
	}
	for _, inter := range interfaces {
		addrs := inter.Addrs
		var macAddress string
		for _, addr := range addrs {
			if strings.Index(addr.Addr, ip) != -1 {
				macAddress = inter.HardwareAddr
			}
		}
		if macAddress != "" {
			return macAddress, nil
		}
	}
	return "", err
}
func Contains(arr []string, str string) bool {
	for _, a := range arr {
		if a == str {
			return true
		}
	}
	return false
}
